<template>
  <div class="course-detail-container" v-loading="loading">
    <!-- 课程头部信息 -->
    <div class="course-header">
      <div class="course-info">
        <el-breadcrumb separator="/">
          <el-breadcrumb-item :to="{ path: '/courses' }">课程</el-breadcrumb-item>
          <el-breadcrumb-item>{{ course.title }}</el-breadcrumb-item>
        </el-breadcrumb>
        
        <h1 class="course-title">{{ course.title }}</h1>
        <p class="course-description">{{ course.description }}</p>
        
        <div class="course-meta">
          <div class="meta-item">
            <el-icon><User /></el-icon>
            <span>{{ course.studentCount || 0 }}人学习</span>
          </div>
          <div class="meta-item">
            <el-icon><Star /></el-icon>
            <span>{{ course.rating || 0 }}分 ({{ course.commentCount || 0 }}评价)</span>
          </div>
          <div class="meta-item">
            <el-icon><Clock /></el-icon>
            <span>{{ course.duration || 0 }}小时</span>
          </div>
          <div class="meta-item">
            <el-icon><Document /></el-icon>
            <span>{{ course.chapterCount || 0 }}章节</span>
          </div>
        </div>
        
        <div class="course-actions">
          <div class="price-info">
            <span v-if="course.price > 0" class="price">¥{{ course.price }}</span>
            <span v-else class="free">免费</span>
          </div>
          
          <div class="action-buttons">
            <el-button 
              v-if="!isEnrolled" 
              type="primary" 
              size="large" 
              @click="handleEnroll"
            >
              立即报名
            </el-button>
            <el-button 
              v-else 
              type="success" 
              size="large" 
              @click="handleContinueLearning"
            >
              继续学习
            </el-button>
            
            <el-button 
              :type="isFavorite ? 'danger' : 'default'" 
              :icon="isFavorite ? StarFilled : Star" 
              @click="toggleFavorite"
            >
              {{ isFavorite ? '已收藏' : '收藏' }}
            </el-button>
          </div>
        </div>
      </div>
      
      <div class="course-cover">
        <img :src="course.cover || '/default-course.jpg'" :alt="course.title" />
      </div>
    </div>

    <!-- 课程内容区域 -->
    <div class="course-content">
      <el-tabs v-model="activeTab" class="course-tabs">
        <el-tab-pane label="课程介绍" name="intro">
          <div class="course-intro">
            <h3>课程目标</h3>
            <ul>
              <li v-for="goal in course.goals" :key="goal">{{ goal }}</li>
            </ul>
            
            <h3>适合人群</h3>
            <ul>
              <li v-for="audience in course.audience" :key="audience">{{ audience }}</li>
            </ul>
            
            <h3>课程大纲</h3>
            <div class="course-outline">
              <div 
                v-for="(chapter, index) in chapters" 
                :key="chapter.id"
                class="chapter-item"
              >
                <div class="chapter-header">
                  <span class="chapter-number">第{{ index + 1 }}章</span>
                  <span class="chapter-title">{{ chapter.title }}</span>
                  <span class="chapter-duration">{{ chapter.duration }}分钟</span>
                </div>
                <div class="chapter-videos">
                  <div 
                    v-for="(video, videoIndex) in chapter.videos" 
                    :key="video.id"
                    class="video-item"
                  >
                    <span class="video-number">{{ index + 1 }}.{{ videoIndex + 1 }}</span>
                    <span class="video-title">{{ video.title }}</span>
                    <span class="video-duration">{{ video.duration }}分钟</span>
                    <el-icon 
                      v-if="video.isCompleted" 
                      color="#67c23a"
                      class="completion-status"
                    >
                      <CircleCheck />
                    </el-icon>
                  </div>
                </div>
              </div>
            </div>
          </div>
        </el-tab-pane>
        
        <el-tab-pane label="课程章节" name="chapters">
          <div class="chapters-list">
            <div 
              v-for="(chapter, index) in chapters" 
              :key="chapter.id"
              class="chapter-card"
            >
              <div class="chapter-header">
                <h4>第{{ index + 1 }}章：{{ chapter.title }}</h4>
                <span class="chapter-meta">{{ chapter.videoCount }}个视频 · {{ chapter.duration }}分钟</span>
              </div>
              
              <div class="chapter-videos">
                <div 
                  v-for="(video, videoIndex) in chapter.videos" 
                  :key="video.id"
                  class="video-card"
                  :class="{ active: currentVideo?.id === video.id }"
                  @click="playVideo(video)"
                >
                  <div class="video-info">
                    <div class="video-number">{{ index + 1 }}.{{ videoIndex + 1 }}</div>
                    <div class="video-details">
                      <h5>{{ video.title }}</h5>
                      <span class="video-duration">{{ video.duration }}分钟</span>
                    </div>
                  </div>
                  
                  <div class="video-actions">
                    <el-progress 
                      v-if="video.progress" 
                      :percentage="video.progress" 
                      :stroke-width="4"
                      :show-text="false"
                      style="width: 60px; margin-right: 12px;"
                    />
                    <el-button 
                      v-if="video.isCompleted" 
                      type="success" 
                      size="small" 
                      :icon="CircleCheck"
                      text
                    >
                      已完成
                    </el-button>
                    <el-button v-else type="primary" size="small" text>
                      开始学习
                    </el-button>
                  </div>
                </div>
              </div>
            </div>
          </div>
        </el-tab-pane>
        
        <el-tab-pane label="课程评论" name="comments">
          <div class="comments-section">
            <div class="comment-form">
              <el-input
                v-model="newComment"
                type="textarea"
                :rows="3"
                placeholder="分享你的学习心得..."
                maxlength="500"
                show-word-limit
              />
              <div class="comment-actions">
                <el-rate v-model="rating" :max="5" show-text />
                <el-button type="primary" @click="submitComment" :loading="submitting">
                  发表评论
                </el-button>
              </div>
            </div>
            
            <div class="comments-list">
              <div 
                v-for="comment in comments" 
                :key="comment.id"
                class="comment-item"
              >
                <div class="comment-avatar">
                  <img :src="comment.avatar || '/default-avatar.jpg'" :alt="comment.username" />
                </div>
                <div class="comment-content">
                  <div class="comment-header">
                    <span class="comment-username">{{ comment.username }}</span>
                    <el-rate 
                      :model-value="comment.rating" 
                      :max="5" 
                      disabled 
                      size="small"
                    />
                    <span class="comment-date">{{ comment.createTime }}</span>
                  </div>
                  <div class="comment-text">{{ comment.content }}</div>
                </div>
              </div>
            </div>
          </div>
        </el-tab-pane>
      </el-tabs>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { ElMessage, ElLoading } from 'element-plus'
import { courseApi } from '@/api/course'
import { 
  User, 
  Star, 
  StarFilled, 
  Clock, 
  Document, 
  CircleCheck 
} from '@element-plus/icons-vue'

const route = useRoute()
const router = useRouter()

// 数据
const course = ref({
  id: '',
  title: '',
  description: '',
  cover: '',
  price: 0,
  studentCount: 0,
  rating: 0,
  commentCount: 0,
  duration: 0,
  chapterCount: 0,
  goals: [],
  audience: []
})

const chapters = ref([])
const comments = ref([])
const loading = ref(false)

// 状态
const activeTab = ref('intro')
const isEnrolled = ref(false)
const isFavorite = ref(false)
const currentVideo = ref(null)

// 评论相关
const newComment = ref('')
const rating = ref(5)
const submitting = ref(false)

// 加载课程详情
const loadCourseDetail = async () => {
  const courseId = route.params.id
  if (!courseId) {
    ElMessage.error('课程ID不能为空')
    return
  }
  
  loading.value = true
  try {
    // 获取课程详情
    const courseResponse = await courseApi.getCourseById(courseId)
    const courseData = courseResponse.data || courseResponse
    
    // 转换数据结构以适配前端组件
    course.value = {
      id: courseData.id,
      title: courseData.courseName || courseData.name,
      description: courseData.intro || courseData.description,
      cover: courseData.coverUrl,
      price: courseData.price || 0,
      studentCount: courseData.studentCount || 0,
      rating: courseData.rating || 0,
      commentCount: courseData.commentCount || 0,
      duration: courseData.duration || 0,
      chapterCount: courseData.chapterCount || 0,
      goals: courseData.goals || [],
      audience: courseData.audience || []
    }
    
    // 获取课程章节
    const chaptersResponse = await courseApi.getChaptersByCourseId(courseId)
    const chaptersData = chaptersResponse.data || chaptersResponse
    chapters.value = Array.isArray(chaptersData) ? chaptersData : []
    
    // 转换章节数据结构
    chapters.value = chapters.value.map(chapter => ({
      id: chapter.id,
      title: chapter.title || chapter.name,
      duration: chapter.duration || 0,
      videos: chapter.videos || [],
      videoCount: chapter.videoCount || 0
    }))
    
    // 获取课程评论
    // 注意：新的API中没有获取评论的接口，暂时注释掉
    // const commentsData = await courseApi.getCourseComments(courseId)
    // comments.value = commentsData || []
    
    // 获取学习进度
    // 注意：新的API中没有获取学习进度的接口，暂时注释掉
    // try {
    //   const progressData = await courseApi.getProgress(courseId)
    //   isEnrolled.value = progressData?.enrolled || false
    //   isFavorite.value = progressData?.favorite || false
    // } catch (error) {
    //   console.warn('获取学习进度失败:', error)
    // }
  } catch (error) {
    console.error('加载课程详情失败:', error)
    ElMessage.error('加载课程详情失败')
  } finally {
    loading.value = false
  }
}

// 处理报名
const handleEnroll = async () => {
  try {
    // 这里应该调用报名API
    ElMessage.success('报名成功！')
    isEnrolled.value = true
  } catch (error) {
    console.error('报名失败:', error)
    ElMessage.error('报名失败')
  }
}

// 继续学习
const handleContinueLearning = () => {
  // 跳转到学习页面
  router.push(`/learning/${course.value.id}`)
}

// 收藏/取消收藏
const toggleFavorite = async () => {
  try {
    if (isFavorite.value) {
      await courseApi.unfavoriteCourse(course.value.id)
      ElMessage.success('已取消收藏')
    } else {
      await courseApi.favoriteCourse(course.value.id)
      ElMessage.success('收藏成功')
    }
    isFavorite.value = !isFavorite.value
  } catch (error) {
    console.error('操作失败:', error)
    ElMessage.error('操作失败')
  }
}

// 播放视频
const playVideo = (video) => {
  currentVideo.value = video
  // 跳转到视频播放页面
  router.push(`/learning/${course.value.id}/video/${video.id}`)
}

// 提交评论
const submitComment = async () => {
  if (!newComment.value.trim()) {
    ElMessage.warning('请输入评论内容')
    return
  }
  
  submitting.value = true
  try {
    const commentData = {
      courseId: course.value.id,
      content: newComment.value,
      rating: rating.value
    }
    
    await courseApi.addComment(commentData)
    ElMessage.success('评论发表成功')
    
    // 重新加载评论
    const commentsData = await courseApi.getCourseComments(course.value.id)
    comments.value = commentsData || []
    
    // 清空表单
    newComment.value = ''
    rating.value = 5
  } catch (error) {
    console.error('发表评论失败:', error)
    ElMessage.error('发表评论失败')
  } finally {
    submitting.value = false
  }
}

onMounted(() => {
  loadCourseDetail()
})
</script>

<style scoped>
.course-detail-container {
  max-width: 1200px;
  margin: 0 auto;
  padding: 20px;
}

.course-header {
  display: flex;
  gap: 30px;
  background: white;
  border-radius: 8px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
  padding: 30px;
  margin-bottom: 20px;
}

.course-info {
  flex: 1;
}

.course-cover {
  width: 300px;
}

.course-cover img {
  width: 100%;
  height: 200px;
  object-fit: cover;
  border-radius: 8px;
}

.course-title {
  font-size: 24px;
  color: #333;
  margin: 10px 0;
}

.course-description {
  color: #666;
  line-height: 1.6;
  margin-bottom: 20px;
}

.course-meta {
  display: flex;
  flex-wrap: wrap;
  gap: 20px;
  margin-bottom: 20px;
}

.meta-item {
  display: flex;
  align-items: center;
  gap: 5px;
  color: #666;
}

.course-actions {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.price-info .price {
  font-size: 24px;
  color: #f56c6c;
  font-weight: bold;
}

.price-info .free {
  font-size: 24px;
  color: #67c23a;
  font-weight: bold;
}

.action-buttons {
  display: flex;
  gap: 10px;
}

.course-content {
  background: white;
  border-radius: 8px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
  padding: 20px;
}

.course-intro h3 {
  margin: 20px 0 10px 0;
  color: #333;
}

.course-intro ul {
  padding-left: 20px;
}

.course-intro li {
  margin: 5px 0;
  line-height: 1.6;
}

.course-outline {
  margin-top: 20px;
}

.chapter-item {
  border: 1px solid #e1e1e1;
  border-radius: 8px;
  margin-bottom: 15px;
  overflow: hidden;
}

.chapter-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 15px 20px;
  background: #f5f7fa;
  font-weight: bold;
}

.chapter-number {
  color: #409eff;
}

.chapter-title {
  flex: 1;
  margin: 0 20px;
}

.chapter-duration {
  color: #999;
}

.chapter-videos {
  padding: 10px 20px;
}

.video-item {
  display: flex;
  align-items: center;
  padding: 8px 0;
  border-bottom: 1px solid #f0f0f0;
}

.video-item:last-child {
  border-bottom: none;
}

.video-number {
  width: 40px;
  color: #999;
}

.video-title {
  flex: 1;
  margin: 0 15px;
}

.video-duration {
  color: #999;
}

.completion-status {
  margin-left: 10px;
}

.chapters-list {
  padding: 10px 0;
}

.chapter-card {
  border: 1px solid #e1e1e1;
  border-radius: 8px;
  margin-bottom: 20px;
  overflow: hidden;
}

.chapter-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 15px 20px;
  background: #f5f7fa;
}

.chapter-header h4 {
  margin: 0;
  color: #333;
}

.chapter-meta {
  color: #999;
  font-size: 14px;
}

.chapter-videos {
  padding: 10px 20px;
}

.video-card {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 15px;
  border: 1px solid #e1e1e1;
  border-radius: 6px;
  margin-bottom: 10px;
  cursor: pointer;
  transition: all 0.3s;
}

.video-card:hover {
  border-color: #409eff;
  background: #f5f9ff;
}

.video-card.active {
  border-color: #409eff;
  background: #ecf5ff;
}

.video-info {
  display: flex;
  align-items: center;
  flex: 1;
}

.video-number {
  width: 30px;
  color: #999;
}

.video-details {
  margin-left: 15px;
}

.video-details h5 {
  margin: 0 0 5px 0;
  color: #333;
}

.video-duration {
  color: #999;
  font-size: 14px;
}

.video-actions {
  display: flex;
  align-items: center;
}

.comments-section {
  padding: 20px 0;
}

.comment-form {
  margin-bottom: 30px;
}

.comment-actions {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-top: 15px;
}

.comments-list {
  border-top: 1px solid #e1e1e1;
  padding-top: 20px;
}

.comment-item {
  display: flex;
  padding: 15px 0;
  border-bottom: 1px solid #f0f0f0;
}

.comment-item:last-child {
  border-bottom: none;
}

.comment-avatar {
  width: 40px;
  height: 40px;
  margin-right: 15px;
}

.comment-avatar img {
  width: 100%;
  height: 100%;
  border-radius: 50%;
  object-fit: cover;
}

.comment-content {
  flex: 1;
}

.comment-header {
  display: flex;
  align-items: center;
  gap: 15px;
  margin-bottom: 10px;
}

.comment-username {
  font-weight: bold;
  color: #333;
}

.comment-date {
  color: #999;
  font-size: 14px;
}

.comment-text {
  line-height: 1.6;
  color: #666;
}

@media (max-width: 768px) {
  .course-header {
    flex-direction: column;
  }
  
  .course-cover {
    width: 100%;
  }
  
  .course-actions {
    flex-direction: column;
    gap: 15px;
    align-items: flex-start;
  }
  
  .comment-item {
    flex-direction: column;
  }
  
  .comment-avatar {
    margin-bottom: 10px;
  }
}
</style>